<template>
  <div class="global-container">
    <div class="global-header">
      <el-image
        style="width: 100px; height: 100px"
        :src="require('@/assets/header_images/current.png')"
      ></el-image>
      <div class="title">
        服务组管理
        <div class="title-content">
          提供以服务组为单位的服务实例管理能力，支持服务组的启动、停止等功能。
        </div>
      </div>
    </div>
    <div class="searchDiv1">
      <div class="searchDiv global-operate">
        <span class="keyword">关键词：</span>
        <el-input
          v-model="searchInput"
          placeholder="通过实例名称检索"
          clearable
          class="inputStyle"
          style="width: 20%"
          prefix-icon="el-icon-search"
          @input="filterServiceInstanceList"
        />
        <div style="float: right">
          <el-button
            type="primary"
            size="small"
            @click="startSelectGroupDeploy"
            class="el-button-primary-style"
            :disabled="startAble"
            >启 动
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="stopSelectGroupDeploy"
            class="el-button-primary-style"
            style="margin-right: 10px"
            >停 止
          </el-button>
          <el-popconfirm
            title="确认删除服务组实例？"
            @confirm="deleteSelectGroupDeploy"
          >
            <el-button
              type="primary"
              size="small"
              slot="reference"
              class="el-button-primary-style"
              style="margin-right: 10px"
              :disabled="selectInstanceList.length === 0"
            >
              删 除
            </el-button>
          </el-popconfirm>
        </div>
      </div>
    </div>
    <div>
      <div class="servicePackageList">
        <div>
          <el-table
            :data="allServiceGroupList"
            style="width: 100%"
            @selection-change="tableSelectionChange"
            ref="multipleTable"
            height="65vh"
          >
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column label="实例名称" width="180">
              <template slot-scope="scope">
                <div>
                  <el-button
                    type="text"
                    @click="getListYamlDeploy(scope.row)"
                    style="padding: 0"
                  >
                    {{ scope.row.groupName }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="描述">
              <template slot-scope="scope">
                <div>
                  <span
                    v-if="
                      scope.row.description === null ||
                      scope.row.description === ''
                    "
                  >
                    暂无描述
                  </span>
                  <span v-else>
                    {{ scope.row.description }}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="创建时间" width="250" />
            <el-table-column prop="status" label="状态" width="130" />
            <el-table-column label="操作" width="280">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  style="padding: 0"
                  @click="getListYamlDeploy(scope.row)"
                >
                  详情
                </el-button>

                <el-button
                  type="text"
                  style="padding: 0"
                  @click="getDeployRelationGraph(scope.row, 'detail')"
                >
                  服务关系图
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-top: 10px; float: right; background-color: blue">
          <el-pagination
            background
            layout="total, prev, pager, next, jumper"
            :total="page.total"
            :page-size="page.pageSize"
            :page.sync="page"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>
    <div>
      <el-dialog
        title="服务组详情"
        :visible.sync="openServiceGroupDetailServiceList"
        width="80%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        center
        :before-close="closeDialog"
      >
        <service-group-detail-service-list-dialog
          :allServiceList="allServiceList"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getTenantId } from "@/utils/tenantId";
import ServiceGroupDetailServiceListDialog from "@/views/ApplicationManage/ServiceGroupManage/ServiceGroupDetailServiceListDialog.vue";
import graphList from "@/views/appstore/graph/graphList.vue";

export default {
  name: "ServiceGroupList",
  components: {
    graphList,
    ServiceGroupDetailServiceListDialog,
  },
  data() {
    return {
      searchInput: "",
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      tmpPage: {
        pageSize: 10,
        pageNum: 1,
        filterKey: "",
        tenantId: "",
      },
      detailType: "",
      startAble: true,
      stopAble: false,
      selectInstanceList: [],
      deployIdss: [],
      status: "",
      allServiceGroupList: [],
      allServiceList: [],
      timer: 0,
      timer1: 0,
      openServiceGroupDetailServiceList: false,
    };
  },
  beforeMount() {
    this.getListGroupDeploy();
  },
  beforeDestroy() {
    clearInterval(this.timer);
    clearInterval(this.timer1);
  },
  methods: {
    getStatusAble(status) {
      const results = [];
      status.forEach((ele) => {
        const parts = ele.split("/");
        const areDifferent = parts[0] !== parts[1];
        results.push(areDifferent);
      });
      this.startAble = !results.every((result) => result === true);
    },
    getListGroupDeploy() {
      setTimeout(() => {
        this.tmpPage.tenantId = getTenantId();
        if (this.tmpPage.tenantId === undefined) {
          this.$router.push("/");
          this.$message.warning("数据出现问题，请稍后再试");
        } else {
          this.$appManageApi.listGroupDeploy(this.tmpPage).then((res) => {
            if (res && res.code === 200) {
              this.allServiceGroupList = res.data.records;
              this.page.total = res.data.total;
            }
          });
        }
      }, 500);
    },
    getCurrentStatus() {
      this.allServiceGroupList.forEach((ele) => {
        this.deployIdss.push(ele.id);
      });
      if (this.deployIdss) {
        this.$appManageApi.getGroupDeployStatus(this.deployIdss).then((res) => {
          if (res && res.code === 200) {
            this.allServiceGroupList.forEach((ele) => {
              let filter = res.data.filter((ele1) => ele1.groupId === ele.id);
              if (filter.length > 0) {
                ele.status = filter[0].status;
              }
            });
          }
        });
      }
    },
    changePage(currentPage) {
      this.page.currentPage = currentPage;
      this.tmpPage.pageNum = currentPage;
      this.getListGroupDeploy();
    },
    getListYamlDeploy(row) {
      clearInterval(this.timer);
      this.$appManageApi
        .listYamlDeploy(row.id)
        .then((res) => {
          if (res && res.code === 200) {
            this.allServiceList = res.data;
            this.getCurrentPageDeployStatus();
            this.openServiceGroupDetailServiceList = true;
            this.timer = setInterval(() => {
              this.getCurrentPageDeployStatus();
            }, 5000);
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    showYamlInfo(row) {
      this.yamlDialog = true;
      this.yamlString = row.pvcYaml;
      this.yamlName = row.pvcName;
    },

    getDeployRelationGraph(row, detailType) {
      this.$router.push({
        name: "GraphList",
        params: {
          serviceGroupInfo: row,
          detailType: detailType,
        },
      });
    },
    filterServiceInstanceList() {
      this.tmpPage.filterKey = this.searchInput;
      this.tmpPage.pageNum = 1;
      this.tmpPage.pageSize = 10;
      this.getListGroupDeploy();
    },
    tableSelectionChange(selectList) {
      const statusValues = selectList.map((item) => item.status);
      this.getStatusAble(statusValues);
      console.log(selectList);
      this.selectInstanceList = selectList;
    },
    startSelectGroupDeploy() {
      if (!this.operateCheck()) {
        return;
      }
      const result = this.openFullScreen2();
      let deployIds = [];
      this.selectInstanceList.forEach((ele) => {
        deployIds.push(ele.id);
      });
      this.$appManageApi
        .startGroupDeploy(deployIds)
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success("服务组启动成功");
            // result.close();
            // this.getListGroupDeploy();
          }
        })
        .catch((error) => {
          result.close();
          this.$message.error(error.message);
        })
        .finally(() => {
          this.getListGroupDeploy();
          result.close();
        });
    },
    stopSelectGroupDeploy() {
      if (!this.operateCheck()) {
        return;
      }
      const result = this.openFullScreen2();
      let deployIds = [];
      this.selectInstanceList.forEach((ele) => {
        deployIds.push(ele.id);
      });
      this.$appManageApi
        .stopGroupDeploy(deployIds)
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success("服务组停止成功");
            this.getListGroupDeploy();
            result.close();
          }
        })
        .catch((error) => {
          result.close();
          this.$message.error(error.message);
        })
        .finally(() => {
          result.close();
        });
    },
    startGroupDeploy(groupId) {
      this.$appManageApi
        .startGroupDeploy([groupId])
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success("服务组启动成功");
            this.getListGroupDeploy();
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    openFullScreen2() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      return loading;
    },
    getCurrentPageDeployStatus() {
      const deployIds = [];
      this.allServiceList.forEach((ele) => {
        deployIds.push({
          deployType: ele.deployType,
          arranged: ele.arranged,
          id: ele.id,
        });
      });

      this.$appManageApi
        .getGroupInstanceDeployStatus(deployIds)
        .then((res) => {
          if (res && res.code === 200) {
            this.allServiceList.forEach((ele) => {
              const deployStatusEle = res.data.filter(
                (element) => ele.id === element.deployId
              )[0];
              let tmpStatus = "";
              switch (deployStatusEle.status) {
                case "NONE":
                  tmpStatus = "未部署";
                  break;
                case "UPDATING":
                  tmpStatus = "更新中";
                  break;
                case "RUNNING":
                  tmpStatus = "运行中";
                  break;
                case "STOPPED":
                  tmpStatus = "已停止";
                  break;
                case "ERROR":
                  tmpStatus = "异常";
                  break;
                default:
                  tmpStatus = "未知";
              }
              ele.deployStatus = tmpStatus;
            });
          } else {
            clearInterval(this.timer);
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    stopGroupDeploy(id) {
      console.log("id", id);
      this.$appManageApi
        .stopGroupDeploy([id])
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success("服务组停止成功");
            this.getListGroupDeploy();
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    deleteSelectGroupDeploy() {
      if (!this.operateCheck()) {
        return;
      }
      let flag = true;
      let selectedDeployId = [];
      console.log("this.selectInstanceList", this.selectInstanceList);
      this.selectInstanceList.forEach((ele) => {
        selectedDeployId.push(ele.id);
      });
      console.log(this.selectedDeployId);
      this.$refs.multipleTable.clearSelection();
      this.$appManageApi.deleteGroupDeploy(selectedDeployId).then((res) => {
        if (res && res.code === 200) {
          this.$message.success(res.msg);
          this.selectInstanceList = [];
          this.$refs.multipleTable.clearSelection();
          this.getListGroupDeploy();
        }
      });
    },
    deleteGroupDeploy(id) {
      this.$appManageApi
        .deleteGroupDeploy([id])
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success("服务组删除成功");
            this.getListGroupDeploy();
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    operateCheck() {
      if (this.selectInstanceList.length === 0) {
        this.$message.warning("请选择数据之后执行操作");
        return false;
      }
      return true;
    },
    closeDialog(done) {
      this.getListGroupDeploy();
      clearInterval(this.timer);
      done();
    },
  },
  mounted() {
    if (this.deployIdss) {
      this.timer1 = setInterval(() => {
        this.getCurrentStatus();
        this.deployIdss = [];
      }, 5000);
    }
  },
};
</script>

<style scoped>
/*::v-deep .el-button--primary {*/
/*  background-color: #304156;*/
/*  border-color: #304156;*/
/*}*/

::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: #304156;
}
</style>
